package deibay.server.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.logging.Level;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import deibay.DeibayLogger;

public class XmlIO {

	public static String DATA_PATH = "data//";
	public static String XML_DATA_BACKUP = ""+XmlDataBackup.class.getSimpleName()+".xml";
	public static String XML_REGISTER = ""+XmlRegisteredUsers.class.getSimpleName()+".xml";
	
	/**
	 * Write a Document (jdom) to path 
	 * @param doc
	 * @param path
	 */
	public static void writeXmltoFile(Document doc, String filename){
				
		Format format =  Format.getPrettyFormat();
		format.setEncoding("UTF-8");
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
				
		OutputStreamWriter writer;
		FileOutputStream fos;
		File f = new File(DATA_PATH+filename);
		
		try {
			fos = new FileOutputStream(f);
			writer = new OutputStreamWriter (fos, "UTF-8");
		    outputter.output(doc, writer);
		    writer.close();
		} catch (IOException e) {			
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao escrever no ficheiro ("+f.getPath()+")"+ e.getMessage()+".\n");
		}        
	}
	
	/**
	 * Read a XML file and returns Jdom Document
	 * 
	 * @param file
	 * @return
	 */
	public static Document readXML(String filename){
		
		Document document = null;		
		SAXBuilder sb = new SAXBuilder();
		File f = new File(DATA_PATH+filename);
		try {			
			document = (Document) sb.build(f);
		}
		catch (JDOMException e) {
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "JDom Exception "+ e.getMessage());	
		}
		catch (IOException e) {
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao ler o ficheiro("+f.getPath()+")"+e.getMessage()+".\n");			
		}		
		return document;		
	}	
}
